package Utils;
####################################################################
#          Keep In Touch - Newsletter Tool for Unix Admins         #
####################################################################

# Copyright (C) 2006 Ashant Chalasani (ashant at yahoo dot com)
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

use strict;
use CGI;
use CGI::Session;
use CGI::Carp qw( fatalsToBrowser warningsToBrowser );
use CGI::Ajax;

use HTML::Template;
use DBI;
use JSON;
use String::Checker;
use Log::Log4perl;

use KitDates;
use KIT_DB;
use Content;
use GUI;
use Recipient;
use Groups;
use Auth;

# Log::Log4perl->init("/home/keepintouch/keepintouch/log.conf");

#	-- This should be set to the path where kit.conf is located
use constant CONFIG_FILE => $ENV{'KIT_CONF'};

our %config			= get_config();
our $kit_db			= new KIT_DB();
our $kit_dates	   = new KitDates();
our $logger       = init_logger();

sub new
{
	my ($class)	= @_;		
	my $self	= {};

	bless $self, 'Utils';
	return $self;
}

sub get_config()
{
    my $self	= shift;
    my %config 	= ();

    open (CONF, CONFIG_FILE) || die "Config file error: " . CONFIG_FILE . "\n" . $!;
    while (<CONF>) {
            my @conf = split('=', $_);
            $config{trim($conf[0])} = trim($conf[1]);
    }

    return %config;
}

sub sendEmail
{
	my ($self, %email)	= @_;

	my $message	= $email{message};
	my $subject	= $email{subject};

	my $sender_email= $email{sender_email};
	my $sender_name	= $email{sender_name};

	my $recp_email	= $email{recipient_email};
	my $recp_name	= $email{recipient_name};

	my $smtp 	= Net::SMTP->new('localhost', Debug => 0);
	print "<h3>Error connecting to SMTP server $!" unless $smtp;

	$smtp->mail("$sender_name <$email{sender_email}>");
	$smtp->to($recp_email);

	$smtp->data();
	$smtp->datasend("To: $recp_email\n");
	$smtp->datasend("From: $sender_name <$email{sender_email}>\n");
	$smtp->datasend("Subject: " . $email{subject} . "\n");
	$smtp->datasend("Content-type: text/html\n\n");
	$smtp->datasend($message);
	$smtp->datasend("\n");

	$smtp->dataend();
	$smtp->quit;
	return;
}

sub trim() 
{
    my $string  = shift;
       $string  =~ s/^\s+// if defined $string;
       $string  =~ s/\s+$// if defined $string;

    return $string;
}

#	-- lists all sqlite database files in DB_PATH_ABS
sub getDBList()
{
    my $self	= shift;
    my $active	= shift || "0,1";

    my @allfiles	= ();

    my $kit_db  = new KIT_DB();
    my @rows	= $kit_db->GetMultipleRows("SELECT id, group_name FROM groups WHERE active IN ($active)");

    foreach (@rows) 
    {
            my %group = (
                    group_id	=> $_->[0],
                    group_name	=> $_->[1],
            );
            push @allfiles, \%group;
    }

    return @allfiles;
}

sub GenerateRandomKey 
{
    my ($self, $passwordsize) 	= @_;

    my @alphanumeric 		= ('a'..'z', 'A'..'Z', 0..9);
    my $rand_key = join '', map $alphanumeric[rand @alphanumeric], 0..$passwordsize;
    return $rand_key;
}

sub init_template
{
    my ($self, $tmpl_file) = @_;

    my %config	= get_config();
    my $htmlTmpl = new HTML::Template
        (
            filename => $config{HTML_TEMPLATE_PATH} . "/" . $tmpl_file,
            die_on_bad_params=> 0,
        ) || die "Error opening HTML template" . $!;

    $htmlTmpl->param('APP_PATH', $config{APP_PATH});
    $htmlTmpl->param('APP_PATH_CGI', $config{APP_PATH_CGI});
    return $htmlTmpl;

}

sub initGUI
{
    my ($self, $tmpl_file, $session) = @_;

    my %config      = get_config();
    my $htmlTmpl    = new HTML::Template
    (
            filename => $config{HTML_TEMPLATE_PATH} . "/" . $tmpl_file,
            die_on_bad_params=> 0,
    )
    || die "Error opening HTML template" . $!;

    my $group;

    my $group_id	=  $session->param('group_id') || 1;

    my $groups	= new Groups();
        $groups->{realm_id}	= $session->param('r_id');

    if ($session->param('r_id'))
    {
        $htmlTmpl->param(DATABASES => [$groups->GetAllGroups(1)]);

        if ($session->param('group_id')) 
        {
                $group	= newFromDB Groups($group_id);
                $htmlTmpl->param('group_name', $group->{group_name});
        }

        $htmlTmpl->param('db_type_desc', Recipient->GetTypeDesc($session->param('db_type')));

        $htmlTmpl->param('db_type_test', 1) if ($session->param('db_type') == 1);
        $htmlTmpl->param('db_type_real', 1) if ($session->param('db_type') == 2);
        $htmlTmpl->param('logged_in', 1);
        $htmlTmpl->param('realm_id', $session->param('r_id'));
        $htmlTmpl->param('username', $session->param('username'));
    }
    else
    {
        $htmlTmpl->param('logged_in', 0);
    }
    
    $htmlTmpl->param('APP_PATH', $config{APP_PATH});
    $htmlTmpl->param('APP_PATH_CGI', $config{APP_PATH_CGI});
    return $htmlTmpl;
}

sub kitSessionInit
{
    my ($self, $q)	= @_;

    my $sid 	= $q->cookie("KIT_CGISESSID") || undef;
    my $session	= new CGI::Session(undef, $sid, {Directory=>'/tmp'});

    my $cookie	= $q->cookie(KIT_CGISESSID => $session->id());
    print $q->header( -cookie => $cookie );

    #   -- Initialize application language
    my $app_lang    = $q->param('app_lang') || 'en';
    $session->param('app_lang', $app_lang);

    if ($q->param('action') =~ /changeDB/) {
            $session->param('group_id', $q->param('group_id'));
            $session->param('db_type', 1);	#	-- just for safety
    }
    if ($q->param('action') =~ /changeDBType/)  {
            $session->param('db_type', $q->param('db_type'));
    }

    return $session;
}

sub GetAllStylesheets
{
	my ($self)	= @_;
	my $stylesheet_path	= "/home/keepintouch/keepintouch/public_html/css";
	my @all_stylesheets	= ();

	opendir STYLE_DIR, $stylesheet_path;
	my @stylesheets	= grep !/^\.\.?$/, readdir STYLE_DIR;

	foreach (@stylesheets) 
	{
		next if ($_ =~ /.svn/);
		my %stylesheet	= (stylesheet => $_);
		push @all_stylesheets, \%stylesheet;

	}
	closedir STYLE_DIR;
	return @all_stylesheets;
}

sub ReadFile
{
	my ($self, $file_name)	= @_;
	my $content_str		= "";
	
	open FILE_CONTENTS, $file_name || die $!;
	while (<FILE_CONTENTS>) {
		$content_str	.= $_;
	}
	return $content_str;
}

sub SetSessionGroup
{
	my ($self, $existing_session, $group_id)	= @_;

# print "sess = " . $existing_session->param('db_type'); exit;

	$existing_session->param('group_id', $group_id);
	$existing_session->param('db_type', 'test');	#	-- just for safety
	return;
}

sub SetSessionDBType
{
	my ($self, $existing_session, $db_type)	= @_;

	$existing_session->param('db_type', $db_type);	#	-- just for safety
	return;
}

#	-- Gets group w. max group_id
sub GetLatestGroup {
    my $self	= shift;
    my $stmt	= "SELECT max(id) AS ret_val FROM groups WHERE active = 1";
    my $kit_db  = new KIT_DB();
    return $kit_db->GetSingleValue($stmt);
}

sub sanitizeApostrophe
{
	my ($self, $raw_string)	= @_;
	$raw_string	=~ s/\'/\\'/g if defined $raw_string;
	$raw_string	=~ s/\"/\\"/g if defined $raw_string;
	return $raw_string;
}

#	-- Validate string using String::Checker
#	 - this doesn't work on min and max
sub checkString
{
	my ($self, $string_to_check, $expectation) = @_;
# 	print "expec = " . $expectation . " | str = " . $string_to_check . "<br>";
	my @checker	= String::Checker::checkstring($string_to_check, [$expectation]);

# 	print "checker = " . $checker[0][0] . "<p>";

	if ($checker[0][0] =~ m/$expectation/) {
		return 0;
	}
	else {
		return 1;
	}
}

#	-- Pops n elements off any Array passed in
sub PopArray
{
	my ($self, $Ary, $n)	= @_;
	
	print $n . "-";
	for (my $i=0; $i<$n; $i++) {
# 		pop @Ary;
		print "stuff-";
	}
# 	return @Ary;
}

##############################################################################################
# Initialize logging
##############################################################################################
sub init_logger
{
    my $self        = shift;
    my ($loglevel)  = @_;

    $loglevel = $config{'LogLevel'} unless defined($loglevel);

    #   -- log to STDOUT (browser or CLI)
#     my $logcfg  = "
#         log4perl.logger.parser           = $loglevel, Screen
#         log4perl.appender.Screen         = Log::Log4perl::Appender::Screen
#         log4perl.appender.Screen.stderr  = 0
#         log4perl.appender.Screen.layout  = Log::Log4perl::Layout::SimpleLayout";

    #   -- log to logfile, defined in kit.conf (variable: logfile)
    my $logfile = $config{'LogFile'};

    my $logcfg  = "
        log4perl.rootLogger=$loglevel, LOGFILE

        log4perl.appender.LOGFILE=Log::Log4perl::Appender::File
        log4perl.appender.LOGFILE.filename=$logfile
        log4perl.appender.LOGFILE.mode=append

        log4perl.appender.LOGFILE.layout=PatternLayout
        log4perl.appender.LOGFILE.layout.ConversionPattern=[%p %r %d] %F{2}(%L) > %m%n";

    Log::Log4perl->init(\$logcfg);
#     my $logger = Log::Log4perl::get_logger("parser");
    my $logger = Log::Log4perl::get_logger();
    return $logger;
}

1;